import string
import random
from django.core.mail import send_mail

from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.http.response import JsonResponse
from .models import CaptchaModel
from django.views.decorators.http import require_http_methods
from .forms import RegisterForm, LoginForm
from django.contrib.auth import get_user_model, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import UserProfile
from django.contrib import messages


User = get_user_model()


# Create your views here.
@require_http_methods(['GET', 'POST'])
def bailogin(request):
    if request.method == 'GET':
        return render(request, 'html/login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录
                login(request, user)
                # 判断是否需要记住我
                if not remember:
                    # 如果点击没有记住我，就要设置过期时间为0，即浏览器关闭后就会消失
                    request.session.set_expiry(0)
                # 如果点击，就什么都不做，使用默认的两周过期时间
                return redirect('/')
            else:
                print('邮箱或密码错误！')
                # form.add_error('email', '邮箱或密码错误！')
                # return render(request, 'html/login.html', context={"form": form})
                return redirect(reverse('baiauth:login'))

def bailogout(request):
    logout(request)
    return redirect(reverse("baiauth:login"))


@require_http_methods(['GET', 'POST'])
def register(request):
    if request.method == 'GET':
        return render(request, 'html/register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            User.objects.create_user(email=email, username=username, password=password)
            return redirect(reverse("baiauth:login"))
        else:
            print(form.errors)
            # 重新跳转到登录页面
            return redirect(reverse('baiauth:register'))
            # return render(request, 'html/register.html', context={"form": form})

def send_email_captcha(request):
    # ?email=xxx
    email = request.GET.get('email')
    if not email:
        return JsonResponse({"code": 400, "message": '必须传递邮箱！'})
    # 生成验证码（取随机的四位阿拉伯数字）
    # ['0', '2', '9', '8']
    captcha = "".join(random.sample(string.digits, 4))
    print(captcha)
    CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': captcha})
    send_mail("白白博客注册验证码", message=f"您的注册验证码是：{captcha}", recipient_list=[email], from_email=None)
    return JsonResponse({"code": 200, "message": "邮箱验证码发送成功！"})


# 个人信息展示页
@login_required
def profile(request):
    # 获取当前用户的Profile（自动创建，避免首次访问为空）
    profile, _ = UserProfile.objects.get_or_create(user=request.user)
    return render(request, 'html/profile.html', {
        'profile': profile,
        'user': request.user  # 用于展示用户ID（username）
    })


# 个人信息编辑页
@login_required
def profile_edit(request):
    profile = get_object_or_404(UserProfile, user=request.user)
    if request.method == 'POST':
        # 接收表单数据并更新
        new_nickname = request.POST.get('nickname', '')
        new_gender = request.POST.get('gender', '')
        new_bio = request.POST.get('bio', '')
        new_region = request.POST.get('region', '')
        new_birthday = request.POST.get('birthday') or None

        if request.FILES.get('avatar'):  # 检查是否有头像文件上传
            profile.avatar = request.FILES.get('avatar')  # 更新头像字段
            is_changed = True  # 标记为已修改（后续会合并其他字段的判断）
        else:
            # 先默认无变化，后续会和其他字段对比
            is_changed = False

        # 对比新数据与原有数据，判断是否有变化
        is_changed = (
                new_nickname != profile.nickname or
                new_gender != profile.gender or
                new_bio != profile.bio or
                new_region != profile.region or
                new_birthday != (profile.birthday.strftime('%Y-%m-%d') if profile.birthday else None)
        )

        # 只有数据有变化时才执行保存
        if is_changed:
            profile.nickname = new_nickname
            profile.gender = new_gender
            profile.bio = new_bio
            profile.region = new_region
            # 处理日期格式
            try:
                profile.birthday = new_birthday
            except ValueError:
                profile.birthday = None
            profile.save()  # 仅当有变化时保存
            messages.success(request, "个人信息已更新")
        else:
            messages.info(request, "未检测到修改，信息保持不变")

        # 无论是否有修改，最终都返回个人简介页
        return redirect('baiauth:profile')

    # GET请求：渲染编辑表单
    return render(request, 'html/profile_edit.html', {'profile': profile})

